//
//  UIImage + Extension.swift
//  微博新浪
//
//  Created by hezerong on 16/6/4.
//  Copyright © 2016年 Rocky. All rights reserved.
//

import UIKit

extension UIImage{

    class func createDotImage(color:UIColor) ->UIImage{
    
    
      //在swift中，结构体是按 “值”传递的，而对象是按 “址“传递的，
        
    
        let size = CGSizeMake(1, 1)
        
       //创建图形上下文
        UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.mainScreen().scale)
        
        //设置颜色
//        let color = UIColor.redColor()
        color.set()

        
        //设置区域填充
        UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //关系图形上下而文
        UIGraphicsEndImageContext()
        
        //获取图片
        return image
        
    }
    
    func async_createCircleImgae (isCornered: Bool = false, size: CGSize, color: UIColor = UIColor.whiteColor(), completion: (UIImage)->()) {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            let rect = CGRect(origin: CGPointZero, size: size)
            //1.开启上下文
            UIGraphicsBeginImageContextWithOptions(size, true, screenScale)
            //2.设置填充颜色
            color.setFill()
            //3. 颜色填充
            UIRectFill(rect)
            
            if isCornered {
                //用贝赛尔曲线裁切
                //设置圆形的裁切路径
                let path = UIBezierPath(ovalInRect: rect)
                path.addClip()
                
            }
            //4. 绘制
            self.drawInRect(rect)
            //5. 生成图片
            let image = UIGraphicsGetImageFromCurrentImageContext()
            //6. 关闭上下文
            UIGraphicsEndImageContext()
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completion(image)
            })
        }
    }
    
    
    
    func createCircleImage(isCornered:Bool,size:CGSize,color:UIColor) ->UIImage{
        
        let rect = CGRect(origin: CGPointZero, size: size)
        
        //1. 开启图形上下文
        UIGraphicsBeginImageContextWithOptions(size, true, screenScale)
        
        //2. 设置填充颜色
        color.setFill()
        
        //3. 颜色填充
        UIRectFill(rect)
        
        //4. 用贝塞尔曲线裁剪
        if isCornered{
        
           let path = UIBezierPath(ovalInRect: rect)
            
            path.addClip()
        }
        
        //5. 绘制
        self.drawInRect(rect)
        
        //6. 生成图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //7. 关闭图形上下文
        UIGraphicsEndImageContext()
    
        return image
       
    }
 
}
